<template>
  <div class="baseinfo">
    <a-form-model ref="ruleForm" :model="form" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
      <a-row :gutter="24">
        <a-col :span="8">
          <a-form-model-item label="项目编号" prop="projectNo" :label-col="{ span: 8 }" :wrapper-col="{ span: 15 }">
            {{ form.projectNo }}
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item
            ref="projectName"
            label="项目名称"
            prop="projectName"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 15 }"
          >
            <a-input
              v-model="form.projectName"
              @blur="
                () => {
                  $refs.projectName.onFieldBlur()
                }
              "
              placeholder="请输入有效的项目名称"  
               :disabled="form.status>1"
            />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item
            ref="mainDeptName"
            label="主导经营体"
            prop="mainDeptName"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 15 }"
          >
            <a-input
              v-model="form.mainDeptName" 
              @blur="
                () => {
                  $refs.mainDeptName.onFieldBlur()
                }
              "
              placeholder="请填写正确的组织架构名称，系统自动校验"
            />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="8">
          <a-form-model-item
            label="项目分类"
            prop="projectTypeSubCategory"
            :disabled="form.id != ''"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 15 }"
          >
            <!-- <a-select
              v-model="form.projectTypeSubCategory"
              placeholder="请选择项目分类"
              :options="projectCategoryOptions" :disabled="form.id!=''"  
            >
              <a-icon slot="suffixIcon" type="plus" />
            </a-select> -->
            <span style="color: #f7a961; margin: 0 6px; font-size: 16px">{{ subName }}</span>
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item
            ref="hatchProjectNo"
            label="孵化项目编号"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 15 }"
          >
            <a-input v-model="form.hatchProjectNo" placeholder="点击选择孵化项目" @click="hatch.visible = true"   :disabled="form.status>1"/>
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item
            ref="hatchProjectName"
            label="孵化项目名称"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 15 }"
          >
            <a-input v-model="form.hatchProjectName" placeholder="点击选择孵化项目" @click="hatch.visible = true"  :disabled="form.status>1"/>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="8">
          <a-form-model-item
            label="上一代项目号"
            prop="lastProjectNo"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 15 }"
          >
            <a-input v-model="form.lastProjectNo" @blur="checkPreProject" />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="上一代项目名称" :label-col="{ span: 8 }" :wrapper-col="{ span: 15 }">
            <a-input v-model="form.lastProjectName" placeholder="自动填充" disabled />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="24">
          <a-form-model-item
            ref="keywords"
            label="关键词"
            prop="keywords"
            :label-col="{ span: 3 }"
            :wrapper-col="{ span: 21 }"
          >
            <a-input
              v-model="form.keywords"
              @blur="
                () => {
                  $refs.keywords.onFieldBlur()
                }
              "
              placeholder="请输入与项目相关的关键词，多个关键词用中文分号[;]隔开，至少填写5个关键词，如：菌种，发酵等"
            />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="8">
          <a-form-model-item
            label="项目所属高企大类"
            prop="highTechType"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 15 }"
          >
            <a-select
              v-model="form.highTechType"
              placeholder="请选择"
              :options="highCategoryOptions"
              @change="highCategoryChange"
            >
              <a-icon slot="suffixIcon" type="plus" />
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="高企项目标识" :label-col="{ span: 8 }" :wrapper-col="{ span: 15 }">
            <a-input placeholder="自动填充" v-model="form.isHighTechProjectText" disabled />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="24">
          <a-form-model-item
            ref="projectContent"
            label="项目内容概述"
            prop="projectContent"
            :label-col="{ span: 3 }"
            :wrapper-col="{ span: 21 }"
          >
            <a-textarea
              v-model="form.projectContent"
              @blur="
                () => {
                  $refs.projectContent.onFieldBlur()
                }
              "
              :auto-size="{ minRows: 3, maxRows: 5 }"
              style="width: 100%"
            />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="24">
          <a-form-model-item
            ref="projectUseFor"
            label="项目应用场景"
            prop="projectUseFor"
            :label-col="{ span: 3 }"
            :wrapper-col="{ span: 21 }"
          >
            <a-textarea
              v-model="form.projectUseFor"
              @blur="
                () => {
                  $refs.projectUseFor.onFieldBlur()
                }
              "
              :auto-size="{ minRows: 3, maxRows: 5 }"
              style="width: 100%"
            />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="24">
          <a-form-model-item
            ref="projectImplement"
            prop="projectImplement"
            :label-col="{ span: 3 }"
            :wrapper-col="{ span: 21 }"
            label="项目实施办法简述"
          >
            <a-textarea
              v-model="form.projectImplement"
              @blur="
                () => {
                  $refs.projectImplement.onFieldBlur()
                }
              "
              :auto-size="{ minRows: 3, maxRows: 5 }"
              style="width: 100%"
            />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="8">
          <a-form-model-item label="是否需要工程动议" prop="isNeedEngineeringMotion">
            <a-radio-group v-model="form.isNeedEngineeringMotion">
              <a-radio :value="true"> 是 </a-radio>
              <a-radio :value="false"> 否 </a-radio>
            </a-radio-group>
            <a-input v-model="form.motionProjectNameOrNo" placeholder="请输入动议项目名称或编号" />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="24">
          <a-form-model-item
            label="设计开发来源"
            prop="designSource"
            :label-col="{ span: 3 }"
            :wrapper-col="{ span: 21 }"
          >
            <a-checkbox-group v-model="form.designSource" :options="designSourceOptions"> </a-checkbox-group>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="24">
          <a-form-model-item
            ref="functionAndPerformance"
            label="功能和性能要求"
            prop="functionAndPerformance"
            :label-col="{ span: 3 }"
            :wrapper-col="{ span: 21 }"
          >            
            <a-textarea
              v-model="form.functionAndPerformance"
              @blur="
                () => {
                  $refs.functionAndPerformance.onFieldBlur()
                }
              "
              :auto-size="{ minRows: 3, maxRows: 5 }"
              style="width: 100%"
              placeholder="基于市场、客户、上下游工序、产品质量安全控制等各类需求、列明项目所设计的产品/工艺/方法等的主要功能和性能（300字以内）"
            />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="24">
          <a-form-model-item
            ref="sourceBefore"
            style="white-space: pre-line"
            class="slot-label"
            prop="sourceBefore"
            :label-col="{ span: 3 }"
            :wrapper-col="{ span: 21 }"
          >
            <span slot="label">来源于以前类似设<p>计和开发活动信息:</p></span>
            <a-textarea
              v-model="form.sourceBefore"
              :auto-size="{ minRows: 3, maxRows: 5 }"
              style="width: 100%"
              placeholder="列明以前是否有类似的设计和开发活动、并列明以前的经验或教训，为本项目提供研发经验和几类（300字以内）"
            />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="24">
          <a-form-model-item
            ref="technologyTarget"
            label="项目目标"
            prop="technologyTarget"
            :label-col="{ span: 3 }"
            :wrapper-col="{ span: 21 }"
          >
            <a-textarea
              v-model="form.technologyTarget"
              @blur="
                () => {
                  $refs.technologyTarget.onFieldBlur()
                }
              "
              :auto-size="{ minRows: 3, maxRows: 5 }"
              style="width: 100%"
              placeholder="填写通过项目研究预计形成什么研究成果（质量优化达到的目标、技术或方法），以及体现所形成研究成果优势的关键评价指标（可量化；若是相对指标，必须列明参比指标的取数口径和比对的周期等信息，若参比对象数据已有，直接写明具体数据）。"
            />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="24">
          <a-form-model-item
            ref="economyTarget"
            label="项目经济目标"
            prop="economyTarget"
            :label-col="{ span: 3 }"
            :wrapper-col="{ span: 21 }"
          >
            <a-textarea
              v-model="form.economyTarget"
              @blur="
                () => {
                  $refs.economyTarget.onFieldBlur()
                }
              "
              :auto-size="{ minRows: 3, maxRows: 5 }"
              style="width: 100%"
              placeholder="填写通过项目研究预计带来什么样的直接或间接经济效益（规模、销值、利润、效率、安全性等提升，或者成本、损耗、劳动力、能耗、安全风险的下降），以及体现所形成效益的关键评价指标（量化且不是相对数值）（300字以内）"
            />
          </a-form-model-item>
        </a-col>
      </a-row>
      
      <five-to-five ref="fiveForm" :projectBuildId="projectBuildId" :change-id="changeId" @addField="addFiveDataToForm"/>
    </a-form-model>

    <pagination-select
      :title="hatch.title"
      :searchPlaceholder="hatch.searchPlaceholder"
      :visible="hatch.visible"
      :url="hatch.url"
      :columns="hatch.columns"
      @hatchHandleOk="hatchHandleOk"
    />
  </div>
</template>
<script>
import $ from 'jquery'
import { getAction, getActionAsync, postAction, postActionAsync } from '@/api/manage'
import { getParamValFromUrl, strNotNull } from '@/utils/common.js'
import Vue from 'vue'
export default {
  components: {
    PaginationSelect: () => import('@/components/tools/PaginationSelect'),
    FiveToFive: () => import('@/components/tools/projectBuildStup/baseInfo/FiveToFive')
  },
  props: {
    projectBuildId: {
      Type: String,
      default: '',
    },
    changeId: {
      Type: String,
      default: '',
    },
    selProjectType: {
      Type: String,
      default: '',
    }
  },
  data() {
    return {
      labelCol: { span: 8 },
      wrapperCol: { span: 15 },
      other: '',
      form: {
        id: '',
        projectClass: '20',
        projectNo: '',
        projectName: '',
        mainDeptName: '',
        projectTypeSubCategory: '',
        hatchProjectId: '',
        hatchProjectNo: '',
        hatchProjectName: '',
        lastProjectNo: '',
        lastProjectName: '',
        keywords: '',
        highTechType: '',
        isHighTechProject: false,
        isHighTechProjectText: '',
        projectContent: '',
        projectUseFor: '',
        projectImplement: '',
        isNeedEngineeringMotion: null,
        motionProjectNameOrNo: '',
        functionAndPerformance: '',
        sourceBefore: '',
        technologyTarget: '',
        economyTarget: '',
        name: '',
        delivery: false,
        type: [],
        resource: '',
        desc: '',
        status: 0 
      },
      rules: {
        projectName: [
          { required: true, message: '请输入有效的项目名', trigger: 'blur' },
          { min: 1, max: 50, message: '项目名不超过50个字符', trigger: 'blur' },
        ],
        keywords: [
          {
            required: true,
            message: '请输入与项目相关的关键词，多个关键词用中文分号[;]隔开，至少填写5个关键词，如：菌种，发酵等',
            trigger: 'blur',
          },
          { min: 1, max: 127, message: '关键词不超过127个字符', trigger: 'blur' },
        ],
        projectContent: [
          { required: true, message: '请输入项目概述', trigger: 'blur' },
          { min: 1, max: 2000, message: '项目概述不超过2000个字符', trigger: 'blur' },
        ],
        projectUseFor: [
          { required: false, message: '请输入项目应用场景', trigger: 'blur' },
          { min: 1, max: 2000, message: '项目应用场景不超过2000个字符', trigger: 'blur' },
        ],
        projectImplement: [
          { required: true, message: '请输入项目实施办法简述', trigger: 'blur' },
          { min: 1, max: 2000, message: '项目实施办法简述不超过2000个字符', trigger: 'blur' },
        ],
        functionAndPerformance: [
          { required: true, message: '请输入功能和性能要求', trigger: 'blur' },
          { min: 1, max: 300, message: '功能和性能要求不超过300个字符', trigger: 'blur' },
        ],
        technologyTarget: [
          { required: true, message: '请输入项目目标', trigger: 'blur' },
          { min: 1, max: 300, message: '项目目标不超过300个字符', trigger: 'blur' },
        ],
        economyTarget: [
          { required: true, message: '请输入项目经济目标', trigger: 'blur' },
          { min: 1, max: 300, message: '项目经济目标不超过300个字符', trigger: 'blur' },
        ],
        mainDeptName: [
          { required: true, message: '请输入主导经营体', trigger: 'blur' },
          { min: 1, max: 300, message: '主导经营体不超过300个字符', trigger: 'blur' },
        ],
        projectTypeSubCategory: [{ required: true, message: '请选择项目分类', trigger: 'change' }],
        highTechType: [{ required: true, message: '请选择项目所属高企大类', trigger: 'change' }],
        designSource: [
          {
            type: 'array',
            required: true,
            message: '请选择设计开发来源',
            trigger: 'blur',
          },
        ],
        isNeedEngineeringMotion: [{ required: true, message: '请选择是否需要工程动议', trigger: 'change' }],
        desc: [{ required: true, message: '请选择是否需要工程动议', trigger: 'blur' }],
      },

      projectCategoryOptions: [],
      highCategoryOptions: [],
      designSourceOptions: [],
      url: {
        codeInfoList: '/manage/codeInfo/list',
        getProjectByNo: '/projectBuild/getProjectByNo',
        save: '/projectBuild/add',
        queryVOById: '/projectBuild/queryVOById',
      },
      hatch: {
        visible: false,
        title: '请选择孵化项目',
        searchPlaceholder: '输入代码或名称查询',
        url: '/hatchProject/listBySelect',
        columns: [
          {
            title: '孵化项目编号',
            dataIndex: 'hatchProjectNo',
            align: 'center',
          },
          {
            title: '孵化项目名称',
            dataIndex: 'hatchProjectName',
            align: 'center',
          },
        ],
      },
      loadFinish: false,
      subName:''
    }
  },
  computed: {},
  methods: {
    addFiveDataToForm(val,valRef) {
      this.$set(this.form, valRef, val)
    },
    async doSubmit() {
      if(!this.loadFinish){
        layer.message.warning('请等待页面加载完毕')
        return {}  
      }
      console.log('this.form.designSource：', this.form.designSource)
      var validR = false
      try {
        validR = await this.$refs.ruleForm.validate()
        validR = await this.$refs.fiveForm.checkFiveWriteStatus()
      } catch (e) {
        validR = false
      }
      console.log('validR', validR)
      this.form.validResult = validR
      let res = await this.doSave()
        this.projectBuildId=res;
      return { valid: validR, id: res }
    },
    async doSave() {
      let flag = null
      var keywords = this.form.keywords
      if (strNotNull(keywords)) {
        let keywordLen = keywords.split('；').filter((x) => !!x).length
        if (keywordLen < 5 || keywordLen > 8) {
          this.$message.warning('请填写5-8个关键词, 中文分号[；]分隔')
          return flag
        }
      }
      var formData = JSON.parse(JSON.stringify(this.form))
      if (formData.designSource!=null && formData.designSource.length>0) {
        formData.designSource = formData.designSource.join(',');
      } else {
        formData.designSource = ''
      }
      formData.changeId=this.changeId;
      var vm = this
      await postActionAsync(this.url.save, formData)
        .then((res) => {
          if (res.code == 200) {
            vm.form.id = res.result.id
            vm.form.projectNo = res.result.projectNo
            this.$message.success('保存成功')
            return (flag = res.result.id)
          } else {
            this.$message.warning('保存数据出错:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('保存数据出错:' + res.message)
        })
      return flag
    },
    resetForm() {
      this.$refs.ruleForm.resetFields()
    },
    //初始化项目子类
    initProjectCategoryOptions() {
      var vm = this
      getAction(this.url.codeInfoList, { type: '项目子类', isdel: 0, parentid: vm.form.projectClass })
        .then((res) => {
          if (res.code == 200) {
            var list = res.result
            if (list != null) {
              list.records.map((item) => {
                vm.projectCategoryOptions.push({ value: item.code, label: item.name })
              })
            }
          } else {
            this.$message.warning('查询项目子类失败:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('查询项目子类失败:' + res.message)
        })
    },
    //初始化项目所属高企大类
    initHighCategoryOptions() {
      var vm = this
      getAction(this.url.codeInfoList, { type: '项目所属高企大类' })
        .then((res) => {
          if (res.code == 200) {
            var list = res.result
            if (list != null) {
              list.records.map((item) => {
                vm.highCategoryOptions.push({ value: item.code, label: item.name })
              })
            }
          } else {
            this.$message.warning('查询项目所属高企大类失败:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('查询项目所属高企大类失败:' + res.message)
        })
    },
    //立项设计来源选项
    initSourceDesign() {
      var vm = this
      getAction(vm.url.codeInfoList, { type: '项目立项设计来源' }).then((res) => {
        if (res.code == 200) {
          res.result.records.forEach((element) => {
            vm.designSourceOptions.push({
              label: element.name,
              value: element.code,
            })
          })
        } else {
          this.$message.warning('加载【项目立项设计来源】选项有误：' + res.message)
        }
      })
    },
    //孵化项目选中
    hatchHandleOk(record) {
      if (record != null && record.length > 0) {
        this.form.hatchProjectId = record[0].id
        this.form.hatchProjectNo = record[0].hatchProjectNo
        this.form.hatchProjectName = record[0].hatchProjectName
      }
      this.hatch.visible = false
    },
    //校验上一代项目号
    checkPreProject() {
      if (this.form.lastProjectNo != null && this.form.lastProjectNo.length > 0) {
        var vm = this
        getAction(this.url.getProjectByNo, { projectNo: this.form.lastProjectNo })
          .then((res) => {
            if (res.code == 200) {
              var result = res.result
              if (result != null) {
                this.form.lastProjectName = result.projectName
              } else {
                this.form.lastProjectNo = ''
                vm.$message.warning('请输入有效的【上一代项目号】')
              }
            } else {
              this.$message.warning('查询上一代项目失败:' + res.message)
            }
          })
          .catch((res) => {
            this.$message.warning('查询上一代项目失败:' + res.message)
          })
      }
    },
    //高企大类变化，设置高企标识
    highCategoryChange() {
      var highCategory = this.form.highTechType
      this.form.isHighTechProjectText =
        highCategory == null || highCategory == '' ? '' : highCategory === '99' ? '非高企项目' : '高企项目'
      if (this.form.isHighTechProjectText == '高企项目') {
        this.form.isHighTechProject = true
      }else{
        this.form.isHighTechProject = false
      }
    },
    //如果有id，则加载已填写信息
    initData() {
      if (this.projectBuildId != null && this.projectBuildId != '') {
        var vm = this
        getAction(this.url.queryVOById, { id: this.projectBuildId,changeId:this.changeId })
          .then((res) => {
            if (res.code == 200) {
              var result = res.result
              if (result != null) {
                this.form = result
                if (this.form.isHighTechProject) {
                  this.form.isHighTechProjectText = '高企项目'
                } else {
                  this.form.isHighTechProjectText = '非高企项目'
                }
                //设计开发来源
                var ds = vm.form.designSource
                if (ds == undefined || ds == null || ds == '') {
                  vm.form.designSource = []
                } else {
                  vm.form.designSource = ds.split(',')
                }
                this.initSubName();
                this.loadFinish=true;
              } else {
                vm.$message.warning('初始化项目信息为空')
              }
            } else {
              this.$message.warning('初始化项目信息失败:' + res.message)
            }
          })
          .catch((res) => {
            this.$message.warning('初始化项目信息失败:' + res.message)
          })
      }else{
        this.loadFinish = true;
      }
    },
    initSubName () {
      var vm = this
      getAction(this.url.codeInfoList, { type: '项目子类', isdel: 0,code:vm.form.projectType,pageSize:-1})
        .then((res) => {
          if (res.code == 200) {
            var list = res.result
            if (list != null) {
              this.subName = list.records[0].name
            }
          } else {
            this.$message.warning('项目子类:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('项目子类:' + res.message)
        })
    },
  },
  mounted() {
    if (this.projectBuildId == null || this.projectBuildId == '') {
        this.form.projectType = this.selProjectType
        this.form.projectTypeSubCategory = this.selProjectType
        this.initSubName()
     }

    this.initProjectCategoryOptions()
    this.initHighCategoryOptions()
    this.initSourceDesign()
    this.initData()
  },
}
</script>
<style lang="less" scoped>
/deep/ .ant-btn-primary {
  width: 85px;
  height: 30px;
  border-radius: 2px;
  background: #4095e4;
  margin-right: 10px;
}
/deep/ .default {
  width: 85px;
  height: 30px;
  border-radius: 2px;
}
.baseinfo {
  background-color: #fff;
  border: 1px solid #eaeaea;
  padding: 30px;
  .btn {
    display: flex;
    justify-content: center;
  }
}
</style>